import { createRouter, createWebHistory } from 'vue-router'
import Layout from '@/layout/Layout.vue'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/auth',
      name: 'Auth',
      component: () => import('@/views/Auth.vue'),
      meta: { title: '登录/注册' }
    },
    {
      path: '/',
      component: Layout,
      children: [
        {
          path: '',
          name: 'Home',
          component: () => import('@/views/Home.vue'),
          meta: { title: '首页' }
        },
        {
          path: 'publish',
          name: 'Publish',
          component: () => import('@/views/Publish.vue'),
          meta: { title: '发布信息' }
        },
        {
          path: 'detail/:id',
          name: 'Detail',
          component: () => import('@/views/Detail.vue'),
          meta: { title: '详情' }
        },
        {
          path: 'user',
          name: 'User',
          component: () => import('@/views/User.vue'),
          meta: { title: '个人中心' }
        },
        {
          path: 'about',
          name: 'About',
          component: () => import('@/views/About.vue'),
          meta: { title: '关于我们' }
        },
        {
          path: 'announcement',
          name: 'Announcement',
          component: () => import('@/views/Announcement.vue'),
          meta: { title: '平台公告' }
        }
      ]
    },
    // 404页面路由
    {
      path: '/:pathMatch(.*)*',
      name: 'NotFound',
      component: () => import('@/views/NotFound.vue'),
      meta: { title: '页面不存在' }
    }
  ]
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 设置页面标题
  document.title = `${to.meta.title} - 失物招领平台`

  // 检查是否需要登录
  const requiresAuth = to.path !== '/auth' && to.path !== '/' && to.path !== '/about' && to.name !== 'NotFound' && to.path !== '/announcement'
  const isAuthenticated = localStorage.getItem('token') // 简单的登录状态检查

  if (requiresAuth && !isAuthenticated) {
    next('/auth')
  } else {
    next()
  }
})

export default router
